# -*- coding: UTF-8 -*-
import os
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_mail_attch():
    # 发送邮箱
    # sender='xxxxx@163.com'
    sender = '756686600@qq.com'
    # 接收邮箱
    receiver = '995595198@qq.com'
    # 发送邮箱服务器
    # smtpserver='smtp.163.com'
    smtpserver = 'smtp.qq.com'
    # 用户名  口令
    # username='18706710668@163.com'
    username = '756686600@qq.com'
    password = 'xxxx'

    # 中文需参数‘utf8’，单字节字符不需要
    # 发送邮件主题
    subject = '日志监控报警'
    msg = MIMEMultipart('mixed')
    msg['Subject'] = Header(subject, 'utf-8')

    # 邮件正文
    text = "Dear all!\n 附件是日志报错内容，请查收~"
    zw = MIMEText(text, 'plain', 'utf-8')
    msg.attach(zw)

    # 邮件附件1
    size_log = os.path.getsize('/data/log/log_err.log')
    if size_log != 0:
        mall_log = open('/data/log/log_err.log', "rb")
        send_log = mall_log.read()
        mall_log.close()
        att_1 = MIMEText(send_log, 'base64', 'utf-8')
        att_1["Content-Type"] = "application/octet-stream"
        att_1["Content-Disposition"] = "attachment;filename = 'log_err.txt'"
        msg.attach(att_1)

    # 邮件附件2
    #size_mall_mg = os.path.getsize('/data/admin/log_err/mall-mg_err.txt')
    #if size_mall_mg != 0:
    #    mall_mg_log = open('/data/admin/log_err/mall-mg_err.txt', "rb")
    #    send_mall_mg_log = mall_mg_log.read()
    #    mall_mg_log.close()
    #    att_2 = MIMEText(send_mall_mg_log, 'base64', 'utf-8')
    #    att_2["Content-Type"] = "application/octet-stream"
    #    att_2["Content-Disposition"] = "attachment;filename = 'mall_mg_err.txt'"
    #    msg.attach(att_2)

    msg['to'] = '995595198@qq.com'
    msg['from'] = '756686600@qq.com'

    smtp = smtplib.SMTP_SSL('smtp.qq.com', port=465)
    # smtp=smtplib.SMTP()
    # smtp.connect('smtp.qq.com')
    # smtp.set_debuglevel(1)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()


if __name__ == '__main__':
    size_log = os.path.getsize('/data/log/log_err.log')
    #size_mall_mg = os.path.getsize('/data/admin/log_err/mall-mg_err.txt')
    if size_log != 0:
        send_mail_attch()
